import store from "@/store/index";
import {
	queryOtherUserInfo,
	addBlockUser,
	queryBatchUserInfo
} from "@/services/user";

import {
	messageClean
} from "@/services/chat";
import {
	querySendSms,
	queryLoginOut
} from "@/services/login";
import {
	queryGroupMemberList
} from "@/services/group";
import vueMain from "@/main.js";
import {
	getCurrencyList
} from "@/services/bourse.js";
import moment from "moment";
import {
	getChatList,
	removeWatchMessage
} from '@/utils/RongIM.js'
import {
	throttle
} from '@/utils/util.js'
import {
	buildI18nTime
} from "@/utils/date-util.js";

import {
	updateInterface,
	logoutInterface
} from '@/utils/olImInterface.js'

import {
	getAppUpdateUrl
} from '@/services/system.js'

import {
	OfflineNotification
} from '@/components/OfflineNotification/index.js';


// 节流形式获取会话
const getChatThrottle = throttle(async function() {
	let res = await getChatList()
	// res = res.filter((o) => o.info && Object.keys(o.info).length !== 0)
	// state.chatList = res
}, 3000)

/**
 * 判断是否在webView环境下
 */
const openInWebview = () => {
  // #ifdef H5
	var ua = navigator.userAgent.toLowerCase()
	if (ua.match(/MicroMessenger/i) == 'micromessenger') { // 微信浏览器判断
		return false
	} else if (ua.match(/QQ/i) == 'qq') { // QQ浏览器判断
		return false
	} else if (ua.match(/WeiBo/i) == "weibo") {
		return false
	} else {
		if (ua.match(/Android/i) != null) {
			return ua.match(/browser/i) == null
		} else if (ua.match(/iPhone/i) != null) {
			return ua.match(/safari/i) == null
		} else {
			return (ua.match(/macintosh/i) == null && ua.match(/windows/i) == null)
		}
	}
  // #endif
  // #ifndef H5
  return false
  // #endif
}


/**
 * 存入webView环境全局唯一标识
 */
const setIsInWebview = () => {
	console.log('是否在webView环境中:', openInWebview());
	// 使用方式
	if (openInWebview()) {
		store.commit('SET_IS_WEBVIEW', true)
		// 在app内打开
		// to do something
	} else {
		store.commit('SET_IS_WEBVIEW', false)
		// 其他地方
		// 发起微信授权
	}
}


// 判断版本是否更新
const isUpdateVersion = async () => {
	const {
		appVersionCode
	} = uni.getSystemInfoSync()
	console.log(appVersionCode, 1212121);
	try {
		const value = uni.getStorageSync('storage_version');
		console.log(value, '获取版本号信息');
		if (value) {
			if (parseInt(appVersionCode) > parseInt(value)) {
				const {
					success,
					result
				} = await getAppUpdateUrl()
				if (success) {
					console.log('获取到的更新路径', result.data.androidComplete);
					updateInterface(result.data.androidComplete)
					uni.setStorageSync('storage_version', appVersionCode);
				}

			}
		} else {
			uni.setStorageSync('storage_version', appVersionCode);
		}
	} catch (e) {
		uni.setStorageSync('storage_version', appVersionCode);
		console.log(e, '获取版本号信息报错');
		// error
	}
}

/**
 * 获取用户当前时间与最后登录时间的时间差
 * * @param time 最后登录时间
 * * @param type 差值的度量单位 years、months、weeks、days、hours、minutes 和 seconds
 * * @param targetTimezone  目标时区，莫斯科东3区，北京东8区,默认为北京时间
 */
const getTimeDiff = (time, type, returnType, targetTimezone = -8) => {
	console.log(time, 'timetime', !time);
	if (!time) {
		return ''
	}
	// 当前时区与中时区时差，以min为维度
	const _dif = new Date().getTimezoneOffset()
	// 本地时区时间 + 时差  = 中时区时间
	// 目标时区时间 + 时差 = 中时区时间
	// 目标时区时间 = 本地时区时间 + 本地时区时差 - 目标时区时差
	// 东9区时间
	const nowTime = new Date().getTime() + _dif * 60 * 1000 - (targetTimezone * 60 * 60 * 1000)
	// const nowTime = new Date().getTime()
	if (returnType) {
		var lang = uni.getLocale()
		var str = ''
		var strTime = ''
		var thisTime = moment(nowTime).diff(time, type)
		const realyTime = String(thisTime) === 'NaN' ? 0 : thisTime
		if (realyTime <= 60) {
			str = lang === 'zh-Hans' ? `最后一次出现在${realyTime}分钟前` : lang === 'en' ?
				`Last seen within ${realyTime} minutes` : `Последнее посещение в течение ${realyTime} минут`
			return str
		} else if (realyTime <= 24 * 60) {
			strTime = parseInt(realyTime / 60)
			str = lang === 'zh-Hans' ? `最后一次出现在${strTime}小时前` : lang === 'en' ?
				`Last seen within ${strTime} hours` : `Последний раз видели в течение ${strTime} часов`
			return str
		} else if (realyTime <= 24 * 60 * 7) {
			strTime = parseInt(realyTime / 60 / 24)
			str = lang === 'zh-Hans' ? `最后一次出现在${strTime}天前` : lang === 'en' ? `Last seen within ${strTime} days` :
				`Последний раз видели в течение ${strTime} дней`
			return str
		} else if (realyTime <= 24 * 60 * 30) {
			strTime = parseInt(realyTime / 60 / 24 / 7)
			str = lang === 'zh-Hans' ? `最后一次出现在${strTime}周前` : lang === 'en' ? `Last seen within ${strTime} weeks` :
				`Последний раз видели в течение ${strTime} недель`
			return str
		} else {
			strTime = buildI18nTime(realyTime)
			str = lang === 'zh-Hans' ? `最后一次出现在${strTime}` : lang === 'en' ? `Last seen within ${strTime}` :
				`Последний раз видел в течение ${strTime}`
			return str
		}
	} else {
		return moment(nowTime).diff(time, type)
	}
}


// 获取通讯录列表
const getUsers = async (isDelete = false, obj) => {
	var data = await queryFriendsList({
		orderByColumn: 'createTime',
		isAsc: 'desc'
	})
	store.commit('SET_FRIENDS_LIST', data.rows)
	if (isDelete) {
		const chatList = store.state.chatList
		// conversationType: 1 私聊, 3 群聊
		const index = chatList.findIndex(
			(item) => item.info.userId === obj.id && item.conversationType === 1
		)
		if (index !== -1) {
			// 只有私聊
			let info = {}
			const data = chatList[index]
			info = await getUserInfo(data.targetId)
			if (info) {
				info.moduleType = 0
			}
			chatList[index].info = info
			store.commit('SET_CHAT_LIST', chatList)
			const nowChat = store.state.roomBaseInfo
			if (nowChat.targetId === chatList[index].targetId) {
				store.commit('SET_ROOM_BASE_INFO', chatList[index])
			}
		}
	}
}

/**
 * 格式化用户信息
 * @param info
 */
const formatUserInfo = (info) => {
	const data = {
		...info,
		showUserName: formatUserName(info),
		showUserAvatar: info.avatar,
		avatarColorCode: info.userVo?.avatarColorCode,
		defaultColor: getDefaultColor(info.userVo?.avatarColorCode),
	};
	data.defaultName = data.showUserName.slice(0, 1);
	return data;
};

/**
 * 从缓存获取用户信息
 * @param userId 用户id
 */
const getUserInfo = async (userId) => {
	let userInfo = {};
	if (userId == store.state.userId) {
		userInfo = store.state.userInfo;
	} else {
		const friendsInfoObj = store.state.OLV1_USER;
		userInfo = friendsInfoObj[userId] ?
			friendsInfoObj[userId] :
			await getTargetUserInfo(userId);
	}
	return userInfo;
};

// 接口获取用户信息
const getTargetUserInfo = async (targetId) => {
	const resp = await queryOtherUserInfo(targetId);
	if (!resp.success || !resp.result.data) return;
	const data = {
		...resp.result.data,
		showUserName: formatUserName(resp.result.data),
		showUserAvatar: resp.result.data.avatar,
		avatarColorCode: resp.result.data.avatarColorCode,
		defaultColor: getDefaultColor(resp.result.data.avatarColorCode),
	};
	data.defaultName = data.showUserName.slice(0, 1);
	updateOlUsersInfo(data)
	//去修改首页单聊会话的
	var chatIndex = store.state.chatList.findIndex(
		(o) =>
		o.conversationType == vueMain.$RongIMLib.ConversationType.PRIVATE &&
		o.targetId == targetId
	);
	if (chatIndex > -1) {
		store.state.chatList[chatIndex].info.showUserName = formatUserName(resp.result.data)
		store.commit("SET_CHAT_LIST", store.state.chatList);
		console.log(resp);
	}
	return data;
};

// 接口批量获取用户信息
const getBatchUserInfo = async (friendIds) => {
	const resp = await queryBatchUserInfo({
		userIds: friendIds
	});
	if (!resp.success || !resp.result.data) return;
	resp.result.data.forEach((item) => {
		item = {
			...item.data,
			showUserName: formatUserName(item),
			showUserAvatar: item.avatar,
			avatarColorCode: item.avatarColorCode,
			defaultColor: getDefaultColor(item.avatarColorCode),
		};
		item.defaultName = item.showUserName.slice(0, 1);
		updateOlUsersInfo(data)
		//去修改首页单聊会话的
		var chatIndex = store.state.chatList.findIndex(
			(o) =>
			o.conversationType == vueMain.$RongIMLib.ConversationType.PRIVATE &&
			o.targetId == item.userId
		);
		if (chatIndex > -1) {
			store.state.chatList[chatIndex].info.showUserName = formatUserName(item)
			store.commit("SET_CHAT_LIST", store.state.chatList);
			console.log(resp);
		}

	})
	console.log(resp.result.data, 'resp.result.data');

	return resp.result.data || [];

};

/**
 * 获取群成员信息
 * @param groupId 群ID
 */
const getGroupMemberInfo = async (groupId) => {
	const groupInfoObj = store.state.groupInfo;
	let list = groupInfoObj[groupId]
	const returnGroupInfo = list && list.length > 1 ? list : (await getGroupMemberList(groupId));
	return returnGroupInfo;
};

// 获取群成员列表
const getGroupMemberList = async (groupId, pageNum = 1, pageSize = 999) => {
	const resp = await queryGroupMemberList({
		pageNum: pageNum,
		pageSize: pageSize,
		groupId: groupId,
	});
	if (!resp.success) return;
	const groupInfoObj = store.state.groupInfo;
	const groupInfoArr = resp.result.rows;
	let groupInfoList = [];
	for (let i = 0; i < groupInfoArr.length; i++) {
		const element = groupInfoArr[i];
		// const userInfo = await getUserInfo(element.userId);
		const data = {
			...element,
			showUserName: element.userVo && formatUserName(element.userVo),
			showUserAvatar: element.userVo && element.userVo.avatar,
			avatarColorCode: element.userVo && element.userVo.avatarColorCode,
			defaultColor: getDefaultColor(
				element.userVo && element.userVo.avatarColorCode
			),
		};

		// data.defaultName = data.showUserName.slice(0, 1)
		data.defaultName = data.showUserName;
		groupInfoList.push(data);
	}
	groupInfoObj[groupId] = groupInfoList;
	store.commit("SET_GROUP_INFO", groupInfoObj);
	return groupInfoObj[groupId];
};

//群主1，管理员2，普通成员3
const getRoleName = (userRole) => {
	let name = "";
	switch (userRole) {
		case 1:
			name = vueMain.$t("OWNER");
			break;
		case 2:
			name = vueMain.$t("ADMIN");
			break;
		case 3:
			name = vueMain.$t("GENNER");
			break;
		default:
			break;
	}
	return name;
};

// 获取群名称/头像
const getGroupInfo = (groupId) => {
	const groupList = store.state.groupList;
	const group = groupList.find((item) => item.groupId == groupId);
	return group;
};

// 修改群聊信息
const updateGroupInfoStore = (option) => {
	var groupList = store.state.groupList;
	var pageChatList = store.state.pageChatList
	var chatList = store.state.chatList
	if (groupList && groupList.length > 0) {
		store.state.groupList = groupList.map(item => {
			if (option.groupId == item.groupId) {
				item = {
					...item,
					...option
				}
			}
			return item
		})
		store.state.pageChatList = pageChatList.map(item => {
			if (option.groupId == item.targetId) {
				item.info = {
					...item.info,
					...option
				}
			}
			return item
		})
		store.state.chatList = chatList.map(item => {
			if (option.groupId == item.targetId) {
				item.info = {
					...item.info,
					...option
				}
			}
			return item
		})
	}
}

// 获取默认头像颜色组
const getDefaultColor = (code) => {
	switch (code) {
		case 0:
			return "linear-gradient(0deg, #5CBDE5 0%, #8BD7F6 100%)";
		case 1:
			return "linear-gradient(0deg, #61BD95 0%, #7CDBB1 100%)";
		case 2:
			return "linear-gradient(0deg, #FD644F 0%, #F28E26 100%)";
		case 3:
			return "linear-gradient(0deg, #FBA980 0%, #F7CB6B 100%)";
		case 4:
			return "linear-gradient(0deg, #7C8AE6 0%, #A8B2F5  100%)";
		default:
			break;
	}
};
// 清除聊天记录
const cleanMessage = async (option) => {
	const resp = await messageClean({
		conversationType: option.conversationType, //会话类型
		targetId: option.targetId || "", //会话id
		msgTimestamp: option.msgTimestamp || "", //清除该时间戳之前的所有历史消息，精确到毫秒，为空时清除该会话的所有历史消息。
	});
	if (!resp.success) return;
	// TODO还需要清空缓存
	const privateChatInfo = delete store.state.privateChatInfo[option.targetId];
	store.commit("SET_PRIVATE_CHAT_INFO", privateChatInfo);
	uni.showToast({
		title: "删除成功",
		icon: "none",
		duration: 1500
	});
	uni.switchTab({
		url: '/pages/chat/Chat'
	});
};
// 加入黑名单
const addBlackUser = async (list, that) => {
	const resp = await addBlockUser({
		blockUserIdList: list,
	});
	if (!resp.success) return false;
	return true
};
// 发送短信
const sendSms = async (phone, areaCode) => {
	const resp = await querySendSms({
		phone,
		areaCode
	});
	if (!resp.success) return;
	uni.showToast({
		title: vueMain.$t("index.operation-success"),
		icon: "none",
		duration: 1500,
	});
};

// 获取币种单位
const getSymbol = async (id) => {
	const currencyList = await getCurrencyList()
	const symbolInfo = currencyList.result.data.filter((item) => item.id === id)
	return symbolInfo
};

const formatUserName = (item) => {
	let userName = ''
	if ((item.commentLast ?? '') || (item.commentName ?? '')) {
		if (item.commentName ?? '') {
			userName += item.commentName + ' '
		}
		if (item.commentLast ?? '') {
			userName += item.commentLast
		}
	} else if (
		item.userVo &&
		((item.userVo.commentName ?? '') || (item.userVo.commentLast ?? ''))
	) {
		if (item.userVo.commentName ?? '') {
			userName += item.userVo.commentName + ' '
		}
		if (item.userVo.commentLast ?? '') {
			userName += item.userVo.commentLast
		}
	} else if ((item.lastName ?? '') || (item.firstName ?? '')) {
		if (item.firstName ?? '') {
			userName += item.firstName + ' '
		}
		if (item.lastName ?? '') {
			userName += item.lastName
		}
	} else if (
		item.userVo &&
		((item.userVo.firstName ?? '') || (item.userVo.lastName ?? ''))
	) {
		if (item.userVo.firstName ?? '') {
			userName += item.userVo.firstName + ' '
		}
		if (item.userVo.lastName ?? '') {
			userName += item.userVo.lastName
		}
	} else {
		userName = item.userName
	}
	return userName
}
// 处理收到的消息
const disposeReceivedMsg = (msgItem) => {
	let chatList = store.state.chatList
	if (chatList.length < 1) {
		getChatThrottle()
		return
	}
	let index = -1
	const currentRoom = chatList.find((t, i) => {
		index = i
		return t.conversationType == msgItem.conversationType && t.targetId == msgItem.targetId
	})
	console.log('找到的房间', currentRoom);
	if (currentRoom && currentRoom.info && Object.keys(currentRoom.info).length !== 0) {
		currentRoom.latestMessage = msgItem
		// 如果是自己再其他端发的消息，则不增加未读数
		if ((msgItem.messageType != 'OL:ReadStatus' && msgItem.messageType != 'RC:RcCmd') && msgItem.senderUserId !==
			store.state.userInfo.userId) {
			currentRoom.unreadMessageCount++
			currentRoom.lastSentTime = getLastUnreadTime(msgItem)
		}
		chatList.splice(index, 1, currentRoom)
	} else {
		getChatThrottle()
	}
	console.log('监听到的消息', msgItem, currentRoom);
}

const getLastUnreadTime = (data) => {
	try {
		if (data.messageType === 'OL:ReadStatus') {
			return data.content.preMsg.latestMessage.sentTime
		} else if (data.messageType === 'RC:RcCmd') {
			return data.content.extra.latestMessage.sentTime
		} else {
			return data.sentTime
		}
	} catch (error) {
		console.log(error)
		return data.sentTime
	}
}

/**
 * 获取系统中的成员信息
 * @param friendIds 需要获取的用户信息id数组
 * @param expiresTime 每个用户信息需要更新的时间,单位 (天)
 */
const getOlUsersInfo = async (friendIds, expiresTime = 7) => {
	// 定义无效的字段
	const InvalidIds = ['OScHVP1tQ', 'system', 'undefined']
	friendIds = friendIds.filter((t) => InvalidIds.indexOf(t) == -1)
	if (friendIds && friendIds.length > 0) {
		const nowTime = Date.now()
		let olUsers = store.state.OLV1_USER
		let newData = []
		// 如果有值则去更新
		if (olUsers && olUsers != '{}' && Object.keys(olUsers).length !== 0) {
			const unSaveIds = []
			friendIds.forEach((t) => {
				if (!olUsers[t]) {
					unSaveIds.push(t)
				} else {
					if (
						nowTime - olUsers[t].saveTime >
						expiresTime * 1000 * 60 * 60 * 24
					) {
						unSaveIds.push(t)
					}
				}
			})
			console.log(unSaveIds.length, 'unSaveIdsunSaveIdsunSaveIds')
			if (unSaveIds.length > 0) {
				console.log(olUsers, friendIds, 'olUsersolUsersolUsersolUsers')
				// 如果存在需要更新的用户信息，则调用接口进行更新
				const resq = await queryBatchUserInfo({
					userIds: unSaveIds.join(',')
				})
				newData = resq.result.data || []
			} else {
				// 如果不存在需要更新的用户信息，则直接返回,不用更新缓存
				return Object.values(olUsers)
			}
		} else {
			olUsers = {}
			// 如果没有缓存则全部取接口的数据
			const resq = await queryBatchUserInfo({
				userIds: friendIds.join(',')
			})
			newData = resq.result.data || []
		}

		// 设置与更新缓存
		const newUserList = olUsers || {}
		newData.forEach((t) => {
			t.saveTime = nowTime

			newUserList[t.userId] = t
		})
		console.log(newUserList, newData, 'newUserListnewUserListnewUserListnewUserList')
		store.commit('SET_OLV1_USER', newUserList)

		return Object.values(newUserList)
	} else {
		return []
	}
}


// 更新单个用户的缓存信息
const updateOlUsersInfo = (data) => {
	const nowTime = Date.now()
	data.saveTime = nowTime
	let olUsers = store.state.OLV1_USER
	if (olUsers && olUsers != '{}' && Object.keys(olUsers).length !== 0) {
		olUsers[data.userId] = data
	} else {
		olUsers = {
			[data.userId]: data
		}
	}
	store.commit('SET_OLV1_USER', olUsers)
}

// 获取和更新单个用户的缓存信息
const getSingleUserInfo = async (id) => {
	const nowTime = Date.now()
	let olUsers = store.state.OLV1_USER
	if (olUsers && olUsers != '{}' && Object.keys(olUsers).length !== 0) {
		if (olUsers[id]) {
			return olUsers[id]
		}
	} else {
		olUsers = {}
	}

	const resq = await queryBatchUserInfo({
		userIds: id
	})
	resq.result.data.forEach((t) => {
		t.saveTime = nowTime
		olUsers[t.userId] = t
	})
	resq.result.data.saveTime = nowTime
	olUsers[id] = resq.result.data[0]
	store.commit('SET_OLV1_USER', olUsers)
	return resq.result.data[0] || []
}


// 更新单个用户的名称信息
const updateOlUsersName = (data) => {
	let olUsers = store.state.OLV1_USER
	if (olUsers && olUsers != '{}' && Object.keys(olUsers).length !== 0) {
		if (olUsers[data.friendId]) {
			olUsers[data.friendId].commentName = data.commentName
			olUsers[data.friendId].commentLast = data.commentLast
			store.commit('SET_OLV1_USER', olUsers)
		}
	}
}

/**
 *   此处为挤号后的操作
 */
const offlineOperate = async () => {
	if(getCurrentPages()[0].route.includes('/Welcome/Welcome')) {
		return
	}
	const resp = await queryLoginOut();
	const myUni = uni
	if (!resp.success) return;
	logoutInterface()
	store.dispatch('changeToken', '')
	store.commit("CLEAR_DATA");
	removeWatchMessage()
	
	OfflineNotification({
		show: true,
		cancleBtn: vueMain.$t('index.Cancel'),
		loginBtn: vueMain.$t('login.Log in'),
		content: vueMain.$t('index.offline-tip')
	}, {
		comfirm(val) {
			this.show = false
			if (val == 'login') {
				myUni.reLaunch({
					url: "/pages/login/Login",
				});
				
			} else {
				myUni.switchTab({
					url: "/",
				});
				
			}
		}
	});
}

export {
	formatUserName,
	formatUserInfo,
	getTimeDiff,
	getGroupMemberInfo,
	getGroupInfo,
	updateGroupInfoStore,
	getRoleName,
	getGroupMemberList,
	getUserInfo,
	getTargetUserInfo,
	getDefaultColor,
	cleanMessage,
	addBlackUser,
	sendSms,
	getSymbol,
	getUsers,
	getBatchUserInfo,
	disposeReceivedMsg,
	getOlUsersInfo,
	updateOlUsersInfo,
	getSingleUserInfo,
	updateOlUsersName,
	setIsInWebview,
	isUpdateVersion,
	offlineOperate
};